<?php

namespace App\Services\Base;
use App\Models\Base\Config;
use App\Models\Base\Regions;
use App\Services\BaseService;
use Illuminate\Support\Facades\Cache;

/**
 * 系统行政区域数据业务类
 *
 * @author WangBin
 * @date 2021-09-24
 * @package App\Http\Services
 */
class RegionService extends BaseService
{
    private $cacheKey = 'hiyee-base-regions';
    /**
     * 获取行政区域（树形）
     *
     * @return array
     */
    public function getTree()
    {
        // 优先去缓存数据
        if(Cache::has($this->cacheKey)) {
            return json_decode(Cache::get($this->cacheKey), true);
        }
        $regions = Regions::all()->toArray();
        $tree = $this->makeTree($regions, 0);
        Cache::put($this->cacheKey, json_encode($tree));
        return $tree;
    }

    /**
     * 生成树形结构
     *
     * @param $data
     * @param int $parentId
     * @return array
     */
    private function makeTree(array $data, int $parentId = 0)
    {
        //第一步 构造数据
        $items = array();
        foreach($data as $value){
            $items[$value['region_id']] = $value;
        }
        //第二部 遍历数据 生成树状结构
        $tree = array();
        foreach($items as $key => $value){
            if(isset($items[$value['parent_id']])){
                $items[$value['parent_id']]['children'][] = &$items[$key];
            }else{
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }
}
